package com.fenquen.dfs.router.protocol;

import com.alibaba.fastjson.JSON;
import com.fenquen.dfs.base.protocol.Protocol;
import com.fenquen.dfs.base.protocol.data.Data;
import com.fenquen.dfs.base.protocol.data.storage_source.req_from_storage.StorageNode;
import com.fenquen.dfs.base.protocol.data.storage_source.req_from_storage.Report;
import com.fenquen.dfs.base.utils.BiUtils;
import com.fenquen.dfs.router.multicast.MulticastServerHandler;
import com.fenquen.dfs.router.rocksdb.RocksDBOperator;
import org.rocksdb.RocksDBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;

@Component
public class ProtocolOperator {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProtocolOperator.class);

    @Autowired
    private RocksDBOperator rocksDBOperator;

    public void getData(ByteBuffer byteBuffer) throws RocksDBException {
        LOGGER.info("router组播接收到的原始数据,{}", BiUtils.byteArr2HexString(byteBuffer.array()));

        // 种类
        byte protocolType = byteBuffer.get();

        // 长度目前尚未用到因为data后边没有内容了
        Short dataLength = byteBuffer.getShort();

        Data data;
        ByteBuffer dataByteBuf = byteBuffer.slice();
        switch (protocolType) {
            case Protocol.ProtocolType.ReqFromStorage.存储节点自身状态信息:
                StorageNode storageNode = new StorageNode();
                storageNode.parseBinary(dataByteBuf);
                storageNode.timestamp = System.currentTimeMillis();
                rocksDBOperator.recordStorageNode(storageNode);
                data = storageNode;
                break;
            case Protocol.ProtocolType.ReqFromStorage.存储节点文件上传回执:
                Report report = new Report();
                report.parseBinary(dataByteBuf);
                rocksDBOperator.recordReport(report);
                data = report;
                break;
            default:
                throw new UnsupportedOperationException();
        }
        LOGGER.info(JSON.toJSONString(data));
    }
}
